import 'package:fl_chart/fl_chart.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:landlore/model/reviewVO.dart';

class ThirdRow extends StatefulWidget {
  final ReviewVO currentMonthData;
  final List<ReviewVO> currentYearList;
  final List<ReviewVO> lastYearList;

  const ThirdRow({
    super.key,
    required this.currentMonthData,
    required this.currentYearList,
    required this.lastYearList,
  });

  @override
  State<ThirdRow> createState() => _ThirdRowState(currentYearList: currentYearList, lastYearList: lastYearList);
}

class _ThirdRowState extends State<ThirdRow> {
  final List<ReviewVO> currentYearList;
  final List<ReviewVO> lastYearList;

  _ThirdRowState({required this.currentYearList,required this.lastYearList,});

  //第三行三卡片点击辅助参数
  bool clickFlag1 = false;
  bool clickFlag2 = false;
  bool clickFlag3 = false;

  //第四行画图联动辅助参数
  int clickType = 1;

  //组装图像数据
  List<FlSpot> spots1_1 = [];
  List<FlSpot> spots1_2 = [];
  List<FlSpot> spots2_1= [];
  List<FlSpot> spots2_2= [];
  List<FlSpot> spots3_1= [];
  List<FlSpot> spots3_2= [];


  @override
  void initState() {
    // TODO: implement initState
    super.initState();

  }

  double fixedDouble(double value,int fixNumber){
    if(value == null){
      return 0;
    }
    return double.parse(value.toStringAsFixed(fixNumber));
  }

  @override
  Widget build(BuildContext context) {
    if(!(spots1_1.isNotEmpty||spots1_2.isNotEmpty||spots2_1.isNotEmpty||spots2_2.isNotEmpty||spots3_1.isNotEmpty||spots3_2.isNotEmpty)){
      //本年数据组装
      for(ReviewVO temp in widget.currentYearList){
        spots1_1.add( FlSpot(temp.createDateMonth!.toDouble()-1,fixedDouble(temp.rent!+temp.otherCharge!,1)));
        spots2_1.add( FlSpot(temp.createDateMonth!.toDouble()-1,fixedDouble(temp.eleCharge!, 1)));
        spots3_1.add( FlSpot(temp.createDateMonth!.toDouble()-1,fixedDouble(temp.waterCharge!, 1)));
      }
      //去年数据组装
      for(ReviewVO temp in widget.lastYearList){
        spots1_2.add( FlSpot(temp.createDateMonth!.toDouble()-1,fixedDouble(temp.rent!+temp.otherCharge!,1)));
        spots2_2.add( FlSpot(temp.createDateMonth!.toDouble()-1,fixedDouble(temp.eleCharge!,1)));
        spots3_2.add( FlSpot(temp.createDateMonth!.toDouble()-1,fixedDouble(temp.waterCharge!,1)));
      }
    }


    return Column(
      children: [
        //========================第三行 三个广告牌部分========================
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          // crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            ThirdCard(
              type: 1,
              value1: widget.currentMonthData.rent!,
              value2: widget.currentMonthData.otherCharge!,
              clicked: clickFlag1,
              callBack: () {
                setState(() {
                  clickFlag1 = true;
                  clickFlag2 = false;
                  clickFlag3 = false;
                  clickType = 1;
                });
              },
            ),
            ThirdCard(
              type: 2,
              value1: widget.currentMonthData.eleAmount!.toDouble(),
              value2: widget.currentMonthData.eleCharge!,
              clicked: clickFlag2,
              callBack: () {
                setState(() {
                  clickFlag2 = true;
                  clickFlag1 = false;
                  clickFlag3 = false;
                  clickType = 2;
                });
              },
            ),
            ThirdCard(
              type: 3,
              value1: widget.currentMonthData.waterAmount!.toDouble(),
              value2: widget.currentMonthData.waterCharge!,
              clicked: clickFlag3,
              callBack: () {
                setState(() {
                  clickFlag3 = true;
                  clickFlag1 = false;
                  clickFlag2 = false;
                  clickType = 3;
                });
              },
            ),
          ],
        ),
        //========================第三行 线形图部分========================
        Stack(alignment: Alignment.center, children: [
          //线形图
          ThirdChart(type: clickType,
            spotsCurrentYear: clickType==1?spots1_1:clickType==2?spots2_1:spots3_1,
            spotsLastYear: clickType==1?spots1_2:clickType==2?spots2_2:spots3_2,),
          //图例
          Positioned(
            bottom: 30.h,
            child: Container(
              color: Colors.grey,
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Container(
                    width: 20.w,
                    height: 20.w,
                    decoration: BoxDecoration(
                        color: clickType == 1
                            ? const Color(0xffff686b)
                            : clickType == 2
                                ? const Color(0xff25a18e)
                                : const Color(0xff00bbf9),
                        border: Border.all(color: Colors.black, width: 2.w),
                        borderRadius: BorderRadius.all(Radius.circular(25.r))),
                  ),
                  Text(
                    '今年数据',
                    style:
                        TextStyle(fontSize: 15.sp, fontWeight: FontWeight.w600),
                  ),
                  SizedBox(width: 20.w),
                  Container(
                    width: 20.w,
                    height: 20.w,
                    decoration: BoxDecoration(
                        color: Colors.yellowAccent,
                        border: Border.all(color: Colors.black, width: 2.w),
                        borderRadius: BorderRadius.all(Radius.circular(25.r))),
                  ),
                  Text(
                    '去年同期',
                    style:
                        TextStyle(fontSize: 15.sp, fontWeight: FontWeight.w600),
                  ),
                  // 添加更多的图例项
                ],
              ),
            ),
          ),
          Positioned(
              top: 0.h,
              left: 5.w,
              child: Row(
                children: [
                  Text(
                    '同期对比',
                    style: TextStyle(
                        fontSize: 45.sp,
                        color: Colors.white.withOpacity(0.9),
                        fontWeight: FontWeight.w900,
                        shadows: const [
                          Shadow(
                              color: Colors.black12,
                              offset: Offset(-2, -4),
                              blurRadius: 3)
                        ]),
                  ),
                ],
              ))
        ]),
      ],
    );
  }
}

class ThirdCard extends StatelessWidget {
  final int type;
  final bool clicked;
  final Function callBack;
  final double value1;
  final double value2;

  const ThirdCard({
    super.key,
    required this.type,
    required this.clicked,
    required this.callBack,
    required this.value1,
    required this.value2,
  });

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () {
        callBack();
      },
      child: AnimatedContainer(
        height: 235.h,
        width: 120.w,
        padding: EdgeInsets.only(top: 15.h, left: 10.w, right: 10.w),
        decoration: BoxDecoration(
            border:
                clicked ? Border.all(color: Colors.white, width: 4.w) : null,
            borderRadius: BorderRadius.all(
              Radius.circular(30.r),
            ),
            gradient: LinearGradient(
                colors: type == 1
                    ? [const Color(0xfff995b3), const Color(0xfffe0549)]
                    : type == 2
                        ? [const Color(0xffa2ebcd), const Color(0xff17cc81)]
                        : [const Color(0xff7797f1), const Color(0xff1d51e7)],
                begin: Alignment.topLeft,
                end: Alignment.bottomRight)),
        duration: const Duration(seconds: 1),
        curve: Curves.ease,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Stack(alignment: Alignment.center, children: [
              Icon(
                type == 1
                    ? Icons.house_rounded
                    : type == 2
                        ? Icons.electric_bolt
                        : Icons.water_drop_rounded,
                size: 30.sp,
                color: Colors.white,
              ),
              Container(
                width: 40.w,
                height: 40.w,
                decoration: BoxDecoration(
                    border: Border.all(color: Colors.white, width: 3.w),
                    borderRadius: BorderRadius.all(Radius.circular(50.r))),
              )
            ]),
            Text(
              type == 1
                  ? '租金'
                  : type == 2
                      ? '用电量'
                      : '用水量',
              style: TextStyle(fontSize: 30.sp, color: Colors.white),
            ),
            Text(
              value1.toStringAsFixed(0),
              style: TextStyle(fontSize: 30.sp, color: Colors.white),
            ),
            // McCountingText(
            //   begin: 0,
            //   end: 9999,
            //   precision: 0,
            //   style: TextStyle(fontSize: 30.sp, color: Colors.white),
            //   duration: type == 1
            //       ? const Duration(milliseconds: 1200)
            //       : type == 2
            //           ? const Duration(milliseconds: 800)
            //           : const Duration(milliseconds: 400),
            //   curve: Curves.fastOutSlowIn,
            // ),
            Divider(
              color: Colors.white70,
              thickness: 2.h,
              height: 2.h,
            ),
            Text(
              type == 1 ? '附加费' : '计费',
              style: TextStyle(fontSize: 25.sp, color: Colors.white),
            ),
            Text(
              value2.toStringAsFixed(0),
              style: TextStyle(fontSize: 30.sp, color: Colors.white),
            ),
            // McCountingText(
            //   begin: 0,
            //   end: type == 1
            //       ? 200
            //       : type == 2
            //           ? 99999
            //           : 99999,
            //   precision: 0,
            //   style: TextStyle(fontSize: 30.sp, color: Colors.white),
            //   duration: type == 1
            //       ? const Duration(milliseconds: 1200)
            //       : type == 2
            //           ? const Duration(milliseconds: 800)
            //           : const Duration(milliseconds: 400),
            //   curve: Curves.fastOutSlowIn,
            // ),
          ],
        ),
      ),
    );
  }
}

class ThirdChart extends StatelessWidget {
  final int type;
  final List<FlSpot> spotsCurrentYear;
  final List<FlSpot> spotsLastYear;

  const ThirdChart({
    super.key,
    required this.type,required this.spotsCurrentYear, required this.spotsLastYear,
  });

  @override
  Widget build(BuildContext context) {
    return AnimatedContainer(
      duration: const Duration(seconds: 1),
      curve: Curves.ease,
      decoration: BoxDecoration(
          borderRadius: BorderRadius.all(Radius.circular(20.r)),
          gradient: LinearGradient(
              colors: type == 1
                  ? [const Color(0xfff995b3), Colors.white70]
                  : type == 2
                      ? [const Color(0xffa2ebcd), Colors.white70]
                      : [const Color(0xff7797f1), Colors.white70],
              begin: Alignment.topCenter,
              end: Alignment.bottomCenter)),
      padding: EdgeInsets.only(left: 0.w, right: 25.w, top: 45.h, bottom: 25.h),
      margin: EdgeInsets.symmetric(vertical: 25.h),
      height: 500.h,
      child: LineChart(
        LineChartData(
            lineTouchData: const LineTouchData(enabled: true),
            minX: 0,
            maxX: 11,
            minY: 0,
            //**********************************坐标部分**********************************
            titlesData: FlTitlesData(
              leftTitles: AxisTitles(
                sideTitles: SideTitles(
                  showTitles: true,
                  getTitlesWidget: leftTitleWidgets,
                  reservedSize: 45.w,
                ),
              ),
              bottomTitles: AxisTitles(
                sideTitles: SideTitles(
                  showTitles: true,
                  getTitlesWidget: bottomTitleWidgets,
                  reservedSize: 40.h,
                ),
              ),
              rightTitles: const AxisTitles(
                sideTitles: SideTitles(
                  showTitles: false,
                ),
              ),
              topTitles: const AxisTitles(
                sideTitles: SideTitles(
                  showTitles: false,
                ),
              ),
            ),

            //**********************************数据部分**********************************
            lineBarsData: [
              //==============================去年数据线==============================
              LineChartBarData(
                gradient: const LinearGradient(
                    colors: [Colors.orange, Colors.orangeAccent],
                    begin: Alignment.bottomCenter,
                    end: Alignment.topCenter),
                // spots: type==1?spots1_2:type==2?spots2_2:spots3_2,
                spots: spotsLastYear,
                //虚线
                // dashArray: [10,12],
                //曲线
                isCurved: true,
                //头尾圆边
                isStrokeCapRound: true,
                //线体宽度
                barWidth: 5.w,
                //线体下方体积部分
                belowBarData: BarAreaData(
                  show: false,
                ),
                //数据点装饰
                dotData: FlDotData(
                  show: true,
                  getDotPainter: (spot, percent, barData, index) =>
                      FlDotCirclePainter(
                    radius: 6.r,
                    color: Colors.yellowAccent,
                    strokeWidth: 2.w,
                    strokeColor: Colors.black,
                  ),
                ),
              ),
              //==============================今年数据线==============================
              LineChartBarData(
                gradient: LinearGradient(
                    colors: type == 1
                        ? [const Color(0xfff995b3), const Color(0xfffe0549)]
                        : type == 2
                            ? [const Color(0xffa2ebcd), const Color(0xff17cc81)]
                            : [
                                const Color(0xff7797f1),
                                const Color(0xff1d51e7)
                              ],
                    begin: Alignment.bottomCenter,
                    end: Alignment.topCenter),
                spots: spotsCurrentYear,
                //虚线
                // dashArray: [10,12],
                //曲线
                isCurved: false,
                //头尾圆边
                isStrokeCapRound: true,
                //线体宽度
                barWidth: 6.w,
                //线体下方体积部分
                belowBarData: BarAreaData(
                  show: true,
                  color: type == 1
                      ? const Color(0xfff995b3).withOpacity(0.5)
                      : type == 2
                          ? const Color(0xffa2ebcd).withOpacity(0.5)
                          : const Color(0xff7797f1).withOpacity(0.5),
                ),
                //数据点装饰
                dotData: FlDotData(
                  show: true,
                  getDotPainter: (spot, percent, barData, index) =>
                      FlDotCirclePainter(
                    radius: 8.r,
                    color: type == 1
                        ? const Color(0xffff686b)
                        : type == 2
                            ? const Color(0xff25a18e)
                            : const Color(0xff00bbf9),
                    strokeWidth: 2.w,
                    strokeColor: Colors.black,
                  ),
                ),
              ),
            ]
            // read about it in the LineChartData section
            ),
        duration: const Duration(milliseconds: 150), // Optional
        curve: Curves.linear, // Optional
      ),
    );
  }
}

Widget bottomTitleWidgets(double value, TitleMeta meta) {
  var style = TextStyle(
    fontWeight: FontWeight.bold,
    fontSize: 16.sp,
  );
  Widget text;
  switch (value.toInt()) {
    case 0:
      text = Text('1月', style: style);
      break;
    case 2:
      text = Text('3月', style: style);
      break;
    case 4:
      text = Text('5月', style: style);
      break;
    case 6:
      text = Text('7月', style: style);
      break;
    case 8:
      text = Text('9月', style: style);
      break;
    case 10:
      text = Text('11月', style: style);
      break;
    default:
      text = Text('', style: style);
      break;
  }

  return SideTitleWidget(
    axisSide: meta.axisSide,
    child: text,
  );
}

Widget leftTitleWidgets(double value, TitleMeta meta) {
  var style = TextStyle(
    fontWeight: FontWeight.bold,
    fontSize: 16.sp,
  );
  Widget text;
  switch (value.toInt()) {
    default:
      text = Text(meta.formattedValue, style: style);
      break;
  }

  return SideTitleWidget(
    axisSide: meta.axisSide,
    child: text,
  );
}
